package com.caipin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caipin.dao.ClassroomDao;
import com.caipin.dao.CourseCurrentDao;
import com.caipin.dao.StudentPhotoDao;
import com.caipin.domain.camera.CourseInfo;
import com.caipin.domain.camera.StudentPhotoInfos;
import com.caipin.domain.table.Classroom;
import com.caipin.domain.table.CourseCurrent;
import com.caipin.domain.table.StudentPhoto;
import com.caipin.service.CameraPlatformManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-08-02 9:47
 * @Description: TODO
 */

@Service
public class CameraPlatformManagementServiceImpl implements CameraPlatformManagementService {
    private static final Logger log = LoggerFactory.getLogger(com.caipin.service.impl.CameraPlatformManagementServiceImpl.class);

    @Autowired
    private ClassroomDao classroomDao;

    @Autowired
    private StudentPhotoDao studentPhotoDao;

    @Autowired
    private CourseCurrentDao courseCurrentDao;

    @Autowired
    private StudentCourseDao studentCourseDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private CourseEventReportService courseEventReportService;

    @Autowired
    private SecurityImageDao securityImageDao;

    @Autowired
    private SecurityCarDao securityCarDao;

    @Autowired
    private SecurityFaceDao securityFaceDao;

    @Autowired
    private SecurityPedestrianDao securityPedestrianDao;

    @Autowired
    private SecurityWarningDao securityWarningDao;

    @Autowired
    private CourseStatisticalRateDao courseStatisticalRateDao;

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private ClassInvasionReportDao classInvasionReportDao;

    @Autowired
    private CheveretoUtils cheveretoUtils;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CourseEventReportDao courseEventReportDao;

    @Autowired
    private SecuritySetParameterDao securitySetParameterDao;

    public StudentPhotoInfos getStudentPhotoInfos(String grade, String clbum) {
        Classroom classroom = (Classroom) this.classroomDao.selectOne((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("grade", grade)).eq("clbum", clbum));
        List<StudentPhoto> studentPhotoList = this.studentPhotoDao.selectList((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("grade", grade)).eq("clbum", clbum));
        if (classroom == null || studentPhotoList == null || studentPhotoList.size() <= 0)
            return null;
        List<StudentPhotoInfos.InfosBean> infosBeanList = new ArrayList<>();
        for (StudentPhoto studentPhoto : studentPhotoList)
            infosBeanList.add((new StudentPhotoInfos.InfosBean())
                    .setStudentId(studentPhoto.getStudentId()).setImg((new StudentPhotoInfos.InfosBean.ImgBean())
                            .setBase64(studentPhoto.getStudentImageBase64()).setFormat("jpeg")));
        StudentPhotoInfos studentPhotoInfos = (new StudentPhotoInfos()).setInfos(infosBeanList).setGrade(grade).setClassroomId(classroom.getClassroomId());
        return studentPhotoInfos;
    }

    public CourseInfo getCourseTableInfos(String classroomId) {
        QueryWrapper<CourseCurrent> queryWrapper = new QueryWrapper();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = simpleDateFormat.format(date);
        String[] cri = classroomId.split("-");
        String building = cri[0];
        String classroom = cri[1];
        ((QueryWrapper) queryWrapper.eq("building", building))
                .eq("classroom", classroom);
        queryWrapper.between("date", dateStr + " 00:00:00", dateStr + " 23:59:59");
        List<CourseCurrent> courseCurrentList = this.courseCurrentDao.selectList((Wrapper) queryWrapper);
        if (courseCurrentList == null || courseCurrentList.size() == 0)
            return null;
        List<CourseInfo.ClassesBean> classesBeanList = new ArrayList<>();
        for (CourseCurrent courseCurrent : courseCurrentList) {
            String[] startTime = courseCurrent.getStartTime().split(":");
            String[] endTime = courseCurrent.getEndTime().split(":");
            CourseInfo.ClassesBean.StartBean startBean = new CourseInfo.ClassesBean.StartBean();
            startBean.setHour(Integer.parseInt(startTime[0])).setMinute(Integer.parseInt(startTime[1]));
            CourseInfo.ClassesBean.EndBean endBean = new CourseInfo.ClassesBean.EndBean();
            endBean.setHour(Integer.parseInt(endTime[0])).setMinute(Integer.parseInt(endTime[1]));
            classesBeanList.add((new CourseInfo.ClassesBean())

                    .setClassId(courseCurrent.getId().toString())
                    .setTeacher(courseCurrent.getTeacherId())
                    .setGrade(courseCurrent.getGrade())
                    .setStart(startBean)
                    .setEnd(endBean));
        }
        CourseInfo courseInfo = (new CourseInfo()).setClassroomId(classroomId).setWeek(((CourseCurrent) courseCurrentList.get(0)).getWeek().toString()).setClasses(classesBeanList);
        return courseInfo;
    }

    public List<String> getStudentIdList(String classId) {
        long classIdLong = Long.parseLong(classId);
        CourseCurrent courseCurrent = (CourseCurrent) this.courseCurrentDao.selectById(Long.valueOf(classIdLong));
        if (courseCurrent == null)
            return null;
        List<String> studentIdList = new ArrayList<>();
        String courseName = courseCurrent.getCourseName();
        if (hasDigit(courseName)) {
            QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper();
            ((QueryWrapper) ((QueryWrapper) ((QueryWrapper) queryWrapper.eq("course_name", courseName))
                    .eq("grade", courseCurrent.getGrade()))
                    .eq("week", courseCurrent.getWeek()))
                    .eq("sections", courseCurrent.getSections());
            List<StudentCourse> studentCourseList = this.studentCourseDao.selectList((Wrapper) queryWrapper);
            for (StudentCourse studentCourse : studentCourseList)
                studentIdList.add(studentCourse.getStudentId());
        } else {
            QueryWrapper<Classroom> queryWrapper = new QueryWrapper();
            ((QueryWrapper) queryWrapper.eq("building_name", courseCurrent.getBuilding()))
                    .eq("classroom_id", courseCurrent.getClassroom());
            Classroom classroom = (Classroom) this.classroomDao.selectOne((Wrapper) queryWrapper);
            QueryWrapper<Student> queryWrapper1 = new QueryWrapper();
            ((QueryWrapper) queryWrapper1.eq("grade", classroom.getGrade()))
                    .eq("clbum", classroom.getClbum());
            List<Student> studentList = this.studentDao.selectList((Wrapper) queryWrapper1);
            for (Student student : studentList)
                studentIdList.add(student.getId());
        }
        return studentIdList;
    }

    public String getStudentPhoto(String studentId) {
        QueryWrapper<StudentPhoto> queryWrapper = new QueryWrapper();
        queryWrapper.eq("student_id", studentId);
        StudentPhoto studentPhoto = (StudentPhoto) this.studentPhotoDao.selectOne((Wrapper) queryWrapper);
        if (studentPhoto == null)
            return null;
        return studentPhoto.getStudentImageBase64();
    }

    public void saveCourseEvent(CourseEvent courseEvent) {
        List<CourseEvent.InfosBean> infos = courseEvent.getInfos();
        if (infos == null || infos.size() <= 0) {
            log.info(courseEvent.toString());
            return;
        }
        List<CourseEventReport> courseEventReportList = new ArrayList<>();
        for (CourseEvent.InfosBean info : courseEvent.getInfos()) {
            Long classIdLong = Long.valueOf(Long.parseLong(courseEvent.getClassId()));
            String[] classroomId = courseEvent.getClassroomId().split("-");
            String s = this.cheveretoUtils.sendImageBase64ToChevereto(info.getImg().getBase64());
            if (s == null) {
                log.error("ImageBase64 is null");
                return;
            }
            String imageSrc = null;
            try {
                CheveretoResult cheveretoResult = (CheveretoResult) this.objectMapper.readValue(s, CheveretoResult.class);
                if (cheveretoResult.getStatus_code() == 200) {
                    imageSrc = cheveretoResult.getImage().getImage().getUrl();
                } else {
                    log.error(cheveretoResult.getError().toString());
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            CourseEventReport courseEventReport = (new CourseEventReport()).setClassId(classIdLong).setBuilding(classroomId[0]).setClassroom(classroomId[1]).setGrade(courseEvent.getGrade()).setAction(info.getAction()).setStartActionTime(str2Date(info.getStartActionTime())).setEndActionTime(str2Date(info.getEndActionTime())).setImageFormat(info.getImg().getFormat()).setImageSrc(imageSrc).setStudentId(info.getStudentId());
            courseEventReportList.add(courseEventReport);
        }
        this.courseEventReportService.saveBatch(courseEventReportList);
    }

    public long saveSecurityEventImage(SecurityEvent securityEvent, String imageBase64) {
        String s = this.cheveretoUtils.sendImageBase64ToChevereto(imageBase64);
        if (s == null) {
            log.error("ImageBase64 is null");
            return 0L;
        }
        String imageSrc = null;
        try {
            CheveretoResult cheveretoResult = (CheveretoResult) this.objectMapper.readValue(s, CheveretoResult.class);
            if (cheveretoResult.getStatus_code() == 200) {
                imageSrc = cheveretoResult.getImage().getImage().getUrl();
            } else {
                log.error(cheveretoResult.getError().toString());
                return 0L;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0L;
        }
        SecurityImage securityImage = (new SecurityImage()).setLocation(securityEvent.getChannelLocation()).setImageSrc(imageSrc).setDeviceId(securityEvent.getDeviceId()).setChannelId(Integer.valueOf(securityEvent.getChannelId())).setSnapTime(securityEvent.getSnapTime());
        this.securityImageDao.insert(securityImage);
        return securityImage.getId().longValue();
    }

    public void saveSecurityEventCar(SecurityCar securityCar) {
        this.securityCarDao.insert(securityCar);
    }

    public void saveSecurityEventFace(SecurityFace securityFace) {
        String s = this.cheveretoUtils.sendImageBase64ToChevereto(securityFace.getChip());
        if (s == null) {
            log.error("ImageBase64 is null");
            return;
        }
        String imageSrc = null;
        try {
            CheveretoResult cheveretoResult = (CheveretoResult) this.objectMapper.readValue(s, CheveretoResult.class);
            if (cheveretoResult.getStatus_code() == 200) {
                imageSrc = cheveretoResult.getImage().getImage().getUrl();
            } else {
                log.error(cheveretoResult.getError().toString());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        securityFace.setChip(null).setImageSrc(imageSrc);
        this.securityFaceDao.insert(securityFace);
    }

    public void saveAnalysisResultStatisticalRate(AnalysisResultRate analysisResultRate) {
        CourseCurrent courseCurrent = (CourseCurrent) this.courseCurrentDao.selectById(analysisResultRate.getClassId());
        if (courseCurrent == null)
            return;
        QueryWrapper<Classroom> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.eq("building_name", courseCurrent.getBuilding()))
                .eq("classroom_id", courseCurrent.getClassroom());
        Classroom classroom = (Classroom) this.classroomDao.selectOne((Wrapper) queryWrapper);
        if (classroom == null)
            return;
        QueryWrapper<Student> queryWrapper1 = new QueryWrapper();
        ((QueryWrapper) queryWrapper1.eq("grade", classroom.getGrade()))
                .eq("clbum", classroom.getClbum());
        Integer count = this.studentDao.selectCount((Wrapper) queryWrapper1);
        Teacher teacher = (Teacher) this.teacherDao.selectById(courseCurrent.getTeacherId());
        if (teacher == null)
            return;
        double percentage = analysisResultRate.getStatisticalRate() / count.intValue() * 100.0D;
        percentage = Math.round(percentage * 100.0D) / 100.0D;
        if ( analysisResultRate.getEventName().equals(") && percentage <= 1.0D)
                percentage = 1.0D - percentage;
        CourseStatisticalRate courseStatisticalRate = (new CourseStatisticalRate()).setGrade(classroom.getGrade()).setClbum(classroom.getClbum()).setTeacherId(teacher.getId()).setTeacherName(teacher.getName()).setBuilding(classroom.getBuildingName()).setClassroom(classroom.getClassroomId()).setCourseName(courseCurrent.getCourseName()).setStudentCount(count).setCourseId(courseCurrent.getId()).setEventName(analysisResultRate.getEventName()).setEventStudentCount(Integer.valueOf(analysisResultRate.getStatisticalRate())).setPercentage(Double.valueOf(percentage)).setCreateTime(new Date());
        this.courseStatisticalRateDao.insert(courseStatisticalRate);
    }

    public void saveInvasionReport(InvasionReport invasionReport) {
        String s = this.cheveretoUtils.sendImageBase64ToChevereto(invasionReport.getImg().getBase64());
        if (s == null) {
            log.error("ImageBase64 is null");
            return;
        }
        String imageSrc = null;
        try {
            CheveretoResult cheveretoResult = (CheveretoResult) this.objectMapper.readValue(s, CheveretoResult.class);
            if (cheveretoResult.getStatus_code() == 200) {
                imageSrc = cheveretoResult.getImage().getImage().getUrl();
            } else {
                log.error(cheveretoResult.getError().toString());
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        String imageSrcOnlyPath = imageSrc.replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
        String[] strings = invasionReport.getClassroomId().split("-");
        if (null == strings || strings.length < 2)
            log.error("classroomId error: ", invasionReport.getClassroomId());
        QueryWrapper<Classroom> classroomQueryWrapper = new QueryWrapper();
        ((QueryWrapper) classroomQueryWrapper.eq("building_name", strings[0]))
                .eq("classroom_id", strings[1]);
        Classroom classroom = (Classroom) this.classroomDao.selectOne((Wrapper) classroomQueryWrapper);
        if (null == classroom) {
            log.error("classroom is null!");
            return;
        }
        this.classInvasionReportDao.insert((new ClassInvasionReport())
                .setClbum(classroom.getClbum())
                .setGrade(classroom.getGrade())
                .setCreateTime(new Date())
                .setHappenTime(invasionReport.getHappenTime())
                .setImgSrc(imageSrcOnlyPath));
    }

    public void saveSecurityPedestrian(SecurityPedestrian securityPedestrian) {
        this.securityPedestrianDao.insert(securityPedestrian);
    }

    public void saveSecurityWarning(SecurityWarning securityWarning) {
        this.securityWarningDao.insert(securityWarning);
    }

    public String createExcelFileInvasionReport(Date startTime, Date endTime, String localAddr) {
        QueryWrapper<ClassInvasionReport> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.between("create_time", startTime, endTime))
                .orderByDesc((Object[]) new String[]{"grade", "clbum"});
        List<ClassInvasionReport> classInvasionReports = this.classInvasionReportDao.selectList((Wrapper) queryWrapper);
        List<ClassInvasionSummaryExcel> classInvasionSummaryExcelList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (ClassInvasionReport classInvasionReport : classInvasionReports)
            classInvasionSummaryExcelList.add((new ClassInvasionSummaryExcel())

                    .setDate(simpleDateFormat.format(classInvasionReport.getCreateTime()))
                    .setGrade(classInvasionReport.getGrade())
                    .setClbum(classInvasionReport.getClbum())
                    .setImageUrl("http://" + localAddr + ":9080" + classInvasionReport.getImgSrc()));
        String filename = "exportClassInvasionSummary" + System.currentTimeMillis();
        String[] headers = {", ", ", "};
        ExportExcel.exportExcel("sheet0", ", headers, classInvasionSummaryExcelList, filename, "");
        return filename;
    }

    public PageBean<ClassInvasionSummaryExcel> findClassroomBreakInList(Date startTime, Date endTime, Integer pageNum, Integer pageSize, String localAddr) {
        Page<ClassInvasionReport> classInvasionReportPage = new Page(pageNum.intValue(), pageSize.intValue());
        QueryWrapper<ClassInvasionReport> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.between("create_time", startTime, endTime))
                .orderByDesc((Object[]) new String[]{"grade", "clbum"});
        Page<ClassInvasionReport> page = (Page<ClassInvasionReport>) this.classInvasionReportDao.selectPage((IPage) classInvasionReportPage, (Wrapper) queryWrapper);
        List<ClassInvasionSummaryExcel> classInvasionSummaryExcelList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (ClassInvasionReport classInvasionReport : page.getRecords())
            classInvasionSummaryExcelList.add((new ClassInvasionSummaryExcel())

                    .setDate(simpleDateFormat.format(classInvasionReport.getCreateTime()))
                    .setGrade(classInvasionReport.getGrade())
                    .setClbum(classInvasionReport.getClbum())
                    .setImageUrl("http://" + localAddr + ":9080" + classInvasionReport.getImgSrc()));
        PageBean<ClassInvasionSummaryExcel> pageBean = new PageBean();
        pageBean.setCurrPage(Long.valueOf(page.getCurrent()));
        pageBean.setPageSize(Integer.valueOf(page.getRecords().size()));
        pageBean.setTotalPage(Long.valueOf(page.getPages()));
        pageBean.setTotalCount(Long.valueOf(page.getTotal()));
        pageBean.setList(classInvasionSummaryExcelList);
        return pageBean;
    }

    public String createExcelFileStrangerWarning(Date startTime, Date endTime, String localAddr) {
        QueryWrapper<SecurityFace> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.between("create_time", startTime, endTime))
                .orderByDesc("channel_id");
        List<SecurityFace> securityFaces = this.securityFaceDao.selectList((Wrapper) queryWrapper);
        List<StrangerWarningExcel> strangerWarningExcelList = new ArrayList<>();
        for (SecurityFace securityFace : securityFaces) {
            SecurityImage securityImage = (SecurityImage) this.securityImageDao.selectById(securityFace.getImageId());
            if (null != securityImage) {
                String path = securityFace.getImageSrc().replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
                String path2 = securityImage.getImageSrc().replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
                strangerWarningExcelList.add((new StrangerWarningExcel())

                        .setDate(securityFace.getCreateTime())
                        .setLocation(securityImage.getLocation())
                        .setFaceImageUrl("http://" + localAddr + ":9080" + path)
                        .setBackgroundImageUrl("http://" + localAddr + ":9080" + path2));
            }
        }
        String filename = "exportStrangerWarning" + System.currentTimeMillis();
        String[] headers = {", ", ", "};
        ExportExcel.exportExcel("sheet0", ", headers, strangerWarningExcelList, filename, "");
        return filename;
    }

    public PageBean<StrangerWarningExcel> findStrangerWarningList(Date startTime, Date endTime, Integer pageNum, Integer pageSize, String localAddr) {
        Page<SecurityFace> securityFacePage = new Page(pageNum.intValue(), pageSize.intValue());
        QueryWrapper<SecurityFace> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.between("create_time", startTime, endTime))
                .orderByDesc("channel_id");
        Page<SecurityFace> page = (Page<SecurityFace>) this.securityFaceDao.selectPage((IPage) securityFacePage, (Wrapper) queryWrapper);
        List<StrangerWarningExcel> strangerWarningExcelList = new ArrayList<>();
        for (SecurityFace securityFace : page.getRecords()) {
            SecurityImage securityImage = (SecurityImage) this.securityImageDao.selectById(securityFace.getImageId());
            if (null != securityImage) {
                String path = securityFace.getImageSrc().replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
                String path2 = securityImage.getImageSrc().replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
                strangerWarningExcelList.add((new StrangerWarningExcel())

                        .setDate(securityFace.getCreateTime())
                        .setLocation(securityImage.getLocation())
                        .setFaceImageUrl("http://" + localAddr + ":9080" + path)
                        .setBackgroundImageUrl("http://" + localAddr + ":9080" + path2));
            }
        }
        PageBean<StrangerWarningExcel> pageBean = new PageBean();
        pageBean.setCurrPage(Long.valueOf(page.getCurrent()));
        pageBean.setPageSize(Integer.valueOf(page.getRecords().size()));
        pageBean.setTotalPage(Long.valueOf(page.getPages()));
        pageBean.setTotalCount(Long.valueOf(page.getTotal()));
        pageBean.setList(strangerWarningExcelList);
        return pageBean;
    }

    public String createExcelFileCrowdWarning(Date startTime, Date endTime, String localAddr) {
        QueryWrapper<SecurityPedestrian> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.between("create_time", startTime, endTime))
                .orderByDesc("channel_id");
        List<SecurityPedestrian> securityPedestrians = this.securityPedestrianDao.selectList((Wrapper) queryWrapper);
        List<CrowdWarningExcel> crowdWarningExcelList = new ArrayList<>();
        for (SecurityPedestrian securityPedestrian : securityPedestrians) {
            SecurityImage securityImage = (SecurityImage) this.securityImageDao.selectById(securityPedestrian.getImageId());
            if (null != securityImage) {
                String path = securityImage.getImageSrc().replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
                crowdWarningExcelList.add((new CrowdWarningExcel())

                        .setDate(securityPedestrian.getCreateTime())
                        .setLocation(securityImage.getLocation())
                        .setPersonCount(securityPedestrian.getCount().toString())
                        .setImageUrl("http://" + localAddr + ":9080" + path));
            }
        }
        String filename = "exportCrowdWarning" + System.currentTimeMillis();
        String[] headers = {", ", ", "};
        ExportExcel.exportExcel("sheet0", ", headers, crowdWarningExcelList, filename, "");
        return filename;
    }

    public PageBean<CrowdWarningExcel> findCrowdWarningList(Date startTime, Date endTime, Integer pageNum, Integer pageSize, String localAddr) {
        Page<SecurityPedestrian> securityPedestrianPage = new Page(pageNum.intValue(), pageSize.intValue());
        QueryWrapper<SecurityPedestrian> queryWrapper = new QueryWrapper();
        ((QueryWrapper) queryWrapper.between("create_time", startTime, endTime))
                .orderByDesc("channel_id");
        Page<SecurityPedestrian> page = (Page<SecurityPedestrian>) this.securityPedestrianDao.selectPage((IPage) securityPedestrianPage, (Wrapper) queryWrapper);
        List<CrowdWarningExcel> crowdWarningExcelList = new ArrayList<>();
        for (SecurityPedestrian securityPedestrian : page.getRecords()) {
            SecurityImage securityImage = (SecurityImage) this.securityImageDao.selectById(securityPedestrian.getImageId());
            if (null != securityImage) {
                String path = securityImage.getImageSrc().replaceFirst("^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+:[0-9]+", "");
                crowdWarningExcelList.add((new CrowdWarningExcel())

                        .setDate(securityPedestrian.getCreateTime())
                        .setLocation(securityImage.getLocation())
                        .setPersonCount(securityPedestrian.getCount().toString())
                        .setImageUrl("http://" + localAddr + ":9080" + path));
            }
        }
        PageBean<CrowdWarningExcel> pageBean = new PageBean();
        pageBean.setCurrPage(Long.valueOf(page.getCurrent()));
        pageBean.setPageSize(Integer.valueOf(page.getRecords().size()));
        pageBean.setTotalPage(Long.valueOf(page.getPages()));
        pageBean.setTotalCount(Long.valueOf(page.getTotal()));
        pageBean.setList(crowdWarningExcelList);
        return pageBean;
    }

    public String createExcelFileCourseStatusSummaryByCourse(Date startTime, Date endTime) {
        QueryWrapper<CourseEventReport> queryWrapper = new QueryWrapper();
        queryWrapper.between("create_time", startTime, endTime);
        List<CourseEventReport> courseEventReports = this.courseEventReportDao.selectList((Wrapper) queryWrapper);
        Map<Long, CourseStatisticalRate> courseStatisticalRateMap = getCourseStatisticalRateMap(startTime, endTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Map<Long, CourseStatusSummaryByCourseExcel> map = new HashMap<>();
        for (CourseEventReport courseEventReport : courseEventReports) {
            CourseStatusSummaryByCourseExcel courseStatusSummaryByCourseExcel = map.get(courseEventReport.getClassId());
            if (null == courseStatusSummaryByCourseExcel) {
                CourseStatusSummaryByCourseExcel value = new CourseStatusSummaryByCourseExcel();
                value.setDate(simpleDateFormat.format(courseEventReport.getCreateTime()));
                if ( courseEventReport.getAction().equals(")) {
                        value.setWalkAroundCount(Integer.valueOf(1));
            } else if ( courseEventReport.getAction().equals(")) {
                    value.setRaiseHandsCount(Integer.valueOf(1));
        } else if ( courseEventReport.getAction().equals(")) {
                value.setSleepCount(Integer.valueOf(1));
    }
        map.put(courseEventReport.getClassId(),value);
        continue;
}
      if(courseEventReport.getAction().equals(")) {
              courseStatusSummaryByCourseExcel.setWalkAroundCount(Integer.valueOf(courseStatusSummaryByCourseExcel.getWalkAroundCount().intValue()+1));
              continue;
              }
              if(courseEventReport.getAction().equals(")) {
              courseStatusSummaryByCourseExcel.setRaiseHandsCount(Integer.valueOf(courseStatusSummaryByCourseExcel.getRaiseHandsCount().intValue()+1));
              continue;
              }
              if(courseEventReport.getAction().equals("))
              courseStatusSummaryByCourseExcel.setSleepCount(Integer.valueOf(courseStatusSummaryByCourseExcel.getSleepCount().intValue()+1));
              }
              List<CourseStatusSummaryByCourseExcel> list=new ArrayList<>();
        for(Map.Entry<Long, CourseStatusSummaryByCourseExcel> entry:map.entrySet()){
        CourseStatusSummaryByCourseExcel value=entry.getValue();
        Long key=entry.getKey();
        CourseStatisticalRate courseStatisticalRate=courseStatisticalRateMap.get(key);
        if(courseStatisticalRate!=null){
        value.setTeacherName(courseStatisticalRate.getTeacherName())
        .setGrade(courseStatisticalRate.getGrade())
        .setClbum(courseStatisticalRate.getClbum())
        .setCourseName(courseStatisticalRate.getCourseName())
        .setAttendance(courseStatisticalRate.getPercentage()+"%");
        list.add(value);
        }
        }
        String filename="exportCourseStatusSummaryByCourse"+System.currentTimeMillis();
        String[]headers={", ",", ",", ",", ","};
        ExportExcel.exportExcel("sheet0",", headers, list, filename, "");
        return filename;
        }

public String createExcelFileCourseStatusSummaryByClassroom(Date startTime,Date endTime){
        QueryWrapper<CourseEventReport> queryWrapper=new QueryWrapper();
        ((QueryWrapper)queryWrapper.between("create_time",startTime,endTime))
        .orderByDesc("grade");
        List<CourseEventReport> courseEventReports=this.courseEventReportDao.selectList((Wrapper)queryWrapper);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Map<String, CourseStatusSummaryByClassroomExcel> map=new HashMap<>();
        for(CourseEventReport courseEventReport:courseEventReports){
        CourseStatusSummaryByClassroomExcel courseStatusSummaryByClassroomExcel=map.get(courseEventReport.getClassroom());
        if(null==courseStatusSummaryByClassroomExcel){
        CourseStatusSummaryByClassroomExcel value=new CourseStatusSummaryByClassroomExcel();
        QueryWrapper<Classroom> queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("classroom_id",courseEventReport.getClassroom());
        Classroom classroom=(Classroom)this.classroomDao.selectOne((Wrapper)queryWrapper1);
        value.setDate(simpleDateFormat.format(courseEventReport.getCreateTime()))
        .setGrade(classroom.getGrade())
        .setClbum(classroom.getClbum());
        if(courseEventReport.getAction().equals(")) {
        value.setWalkAroundCount(Integer.valueOf(1));
        }else if(courseEventReport.getAction().equals(")) {
        value.setRaiseHandsCount(Integer.valueOf(1));
        }else if(courseEventReport.getAction().equals(")) {
        value.setSleepCount(Integer.valueOf(1));
        }
        map.put(courseEventReport.getClassroom(),value);
        continue;
        }
        if(courseEventReport.getAction().equals(")) {
        courseStatusSummaryByClassroomExcel.setWalkAroundCount(Integer.valueOf(courseStatusSummaryByClassroomExcel.getWalkAroundCount().intValue()+1));
        continue;
        }
        if(courseEventReport.getAction().equals(")) {
        courseStatusSummaryByClassroomExcel.setRaiseHandsCount(Integer.valueOf(courseStatusSummaryByClassroomExcel.getRaiseHandsCount().intValue()+1));
        continue;
        }
        if(courseEventReport.getAction().equals("))
        courseStatusSummaryByClassroomExcel.setSleepCount(Integer.valueOf(courseStatusSummaryByClassroomExcel.getSleepCount().intValue()+1));
        }
        List<CourseStatusSummaryByClassroomExcel> list=new ArrayList<>();
        for(Map.Entry<String, CourseStatusSummaryByClassroomExcel> entry:map.entrySet())
        list.add(entry.getValue());
        String filename="exportCourseStatusSummaryByClassroom"+System.currentTimeMillis();
        String[]headers={", ",", ",", "};
        List<CourseStatusSummaryByClassroomExcel> collect=(List<CourseStatusSummaryByClassroomExcel>)list.stream().sorted(Comparator.comparing(CourseStatusSummaryByClassroomExcel::getGrade)).collect(Collectors.toList());
        ExportExcel.exportExcel("sheet0",", headers, collect, filename, "");
        return filename;
        }

public void updatePedestrianThreshold(Integer i){
        SecuritySetParameter securitySetParameter=(new SecuritySetParameter()).setId(Integer.valueOf(1)).setPedestrianThreshold(i);
        this.securitySetParameterDao.updateById(securitySetParameter);
        }

public int getPedestrianThreshold(){
        return((SecuritySetParameter)this.securitySetParameterDao.selectById(Integer.valueOf(1))).getPedestrianThreshold().intValue();
        }

private Map<Long, CourseStatisticalRate> getCourseStatisticalRateMap(Date startTime,Date endTime){
        QueryWrapper<CourseStatisticalRate> queryWrapper=new QueryWrapper();
        ((QueryWrapper)queryWrapper.between("create_time",startTime,endTime))
        .eq("event_name",");
        List<CourseStatisticalRate> courseStatisticalRates=this.courseStatisticalRateDao.selectList((Wrapper)queryWrapper);
        Map<Long, CourseStatisticalRate> map=new HashMap<>();
        for(CourseStatisticalRate courseStatisticalRate:courseStatisticalRates)
        map.put(courseStatisticalRate.getCourseId(),courseStatisticalRate);
        return map;
        }

private boolean hasDigit(String content){
        boolean flag=false;
        Pattern p=Pattern.compile(".*\\d+.*");
        Matcher m=p.matcher(content);
        if(m.matches())
        flag=true;
        return flag;
        }

private Date str2Date(String dateStr){
        Date date=null;
        try{
        date=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(dateStr);
        }catch(ParseException e){
        e.printStackTrace();
        }
        return date;
        }
        }
